﻿import paho.mqtt.client as mqtt
import time


class node_red_msg_reader:
    
    def __init__(self,topic,msg_callback):
        self.topic = topic
        self.client = mqtt.Client()
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
        self.msg_process_callback = msg_callback
        
        
        
    def disconnect(self):
        self.client.disconnect()
        print("监听释放")

    

    # MQTT 连接回调函数
    def on_connect(self,client, userdata, flags, rc):
        print("Connected with result code " + str(rc))
        client.subscribe(self.topic)
        print(f"Subscribed to topic: {self.topic}")
    
    # MQTT 消息处理函数
    def on_message(self,client, userdata, message):
        print(f"Received message: {message.payload.decode()} on topic: {message.topic}")
        msgData = message.payload.decode()
        # 使用外部回调函数处理消息
        self.msg_process_callback(msgData)
       
       
    def on_disconnect(self):
        print("DisConnected with result code ")


    def connect(self):
        while True:
            try:
                self.client.connect("localhost", 1883, 60)  # 尝试连接到本地的 MQTT Broker
                break  # 连接成功后跳出循环
            except ConnectionRefusedError:
                print("MQTT Broker not available, retrying in 5 seconds...")
                time.sleep(5)
        
        # 开启监听
        self.client.loop_start()
    

        